package utweight

import (
	"math/rand"
	"time"
)

type weightNode struct {
	Index int
	Min   int
	Max   int
}

func GetNodeMap(weights []int) (int, map[int]weightNode) {
	nodeMap := make(map[int]weightNode)
	min := 0
	max := 0
	for index, weight := range weights {
		max += weight
		node := weightNode{Index: index, Min: min, Max: max}
		nodeMap[index] = node
		min += weight
	}

	//fmt.Println("weights", weights)
	//fmt.Println("max", max)
	//fmt.Println("nodeMap", nodeMap)
	return max, nodeMap
}
func Get(max int, nodeMap map[int]weightNode) int {
	rd := rand.Intn(max)
	//fmt.Println("rd", rd)
	for k, v := range nodeMap {
		if rd >= v.Min && rd < v.Max {
			return k
		}
	}
	return 0
}
func GetSingle(weights []int) int {
	if len(weights) <= 0 {
		return -1
	}
	max, nodeMap := GetNodeMap(weights)
	rand.Seed(time.Now().UnixNano())
	return Get(max, nodeMap)
}

func GetMultiple(weights []int, count int) []int {
	if len(weights) <= 0 || count <= 0 {
		return []int{}
	}
	max, nodeMap := GetNodeMap(weights)
	rand.Seed(time.Now().UnixNano())
	var result []int
	for i := 0; i < count; i++ {
		result = append(result, Get(max, nodeMap))
	}
	return result
}
